from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, QString
from .facebox import Facebox
from .image_button import ImageButton

class StoryboxMain(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)

		bg = QtGui.QLabel(self) 
		bg.setGeometry(0, 0, 1024, 155)
		path = "resources/storybox_main.png"
		bg.setPixmap(QtGui.QPixmap(path))

		text = QtGui.QLabel(self) 
		text.setGeometry(78, 22, 873, 110)
		font = QtGui.QFont("White Rabbit", 24)
		text.setFont(font)
		text.setStyleSheet("color:green")
		text.setText("The plan was to travel to the desert city of Abby's Crossing.")
		text.setAlignment(Qt.AlignTop|Qt.AlignLeft)
		self.text = text
		text.setWordWrap(True)

	def set_text(self, s):
		self.text.setText(s)

class StoryboxNamer(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)

		bg = QtGui.QLabel(self) 
		bg.setGeometry(0, 0, 204, 89)
		path = "resources/facebox_namer.png"
		bg.setPixmap(QtGui.QPixmap(path))

		text = QtGui.QLabel(self) 
		text.setGeometry(11, 32, 182, 24)
		font = QtGui.QFont("White Rabbit", 18)
		text.setFont(font)
		text.setStyleSheet("color:green")
		text.setText("Narrator")
		text.setAlignment(Qt.AlignVCenter|Qt.AlignHCenter)
		self.text = text

	def set_name(self, name):
		print "setting name ", name
		self.text.setText(name)

class StoryboxMore(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)

		self.more = ImageButton("more_butt", self,
			"resources/facebox_more.png",
			"resources/facebox_more_h.png",
			"resources/facebox_more_d.png",
			"resources/facebox_more.png",
		)
		self.more.setGeometry(0, 0, 132, 37)
		self.more.clicked.connect(self.clicked)

	clicked = QtCore.pyqtSignal()

class Storybox(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)

		gantry = QtGui.QLabel(self) 
		gantry.setGeometry(816, 0, 179, 228)
		path = "resources/facebox_gantry.png"
		gantry.setPixmap(QtGui.QPixmap(path))
		gantry.hide()
		self.gantry = gantry

		namer = StoryboxNamer(self)
		namer.setGeometry(64,138,204, 89)
		namer.hide()
		self.namer = namer

		face = Facebox(self)
		face.move(740,32)
		face.hide()
		self.face = face

		box = StoryboxMain(self)
		box.setGeometry(0,222,1024, 370)
		self.box = box

		more = StoryboxMore(self)
		more.move(822,370)
		more.clicked.connect(self.clicked)
		self.more = more

	clicked = QtCore.pyqtSignal()

	def set_name(self, name):
		if name == None:
			self.namer.hide()
			return
		self.namer.show()
		self.namer.set_name(name)

	def set_main(self, s):
		self.box.set_text(s)
		
	def set_face(self, path):
		if path == None:
			self.face.hide()
			self.gantry.hide()
			return
		self.face.show()
		self.gantry.show()
		self.face.set_face(path)

	def show_more(self, vis):
		self.more.setVisible(vis)

class StoryboxStage(QtGui.QWidget):
        def __init__(self, *args, **kw):
		QtGui.QWidget.__init__(self, *args, **kw)
		self.opts = None

		self.bg = QtGui.QLabel(self) 
		self.bg.setGeometry(0, 0, 1024, 768)
		path = "resources/wood.jpg"
		#bg.setPixmap(QtGui.QPixmap(path))

		self.storybox = Storybox(self)
		self.storybox.move(0,350)
		self.storybox.clicked.connect(self.next)

	def set_scene(self, path):
		self.bg.setPixmap(QtGui.QPixmap(path))
		

	def set_main(self, s):
		self.storybox.set_main(s)
		

	def show_more(self, vis):
		self.storybox.show_more(vis)

	def set_face(self, s):
		self.storybox.set_face(s)
		

	def set_name(self, s):
		self.storybox.set_name(s)
		

	def set_menu(self, opts):
		buff = ""
		for i, tup in enumerate(opts):
			buff += "{}: {}\n".format(
				i+1, tup[0]
			)
		self.storybox.set_main(buff)
		self.opts = opts
		print "self.opts = ", self.opts
		self.show_more(False)
		
	def keyPressEvent(self,e):
		k = e.key()
		if self.opts == None:
			return
		if k == ord("1"):
			print "extending script with ", self.opts[0][1]
			self.script.extend(self.opts[0][1]);
		if k == ord("2"):
			self.script.extend(self.opts[1][1]);
		if k == ord("3"):
			self.script.extend(self.opts[2][1]);
		self.show_more(True)
		self.next()

	def play(self, ll):
		self.script = ll[:]
		self.next()

	ended = QtCore.pyqtSignal()

	def next(self):
#
#		end of list case:
#
#		blank out the screen and send a signal
#
		if self.script == None or self.script == []:
			self.set_main("")
			self.ended.emit()
			return
#
#		get the current item
#
		item = self.script.pop(0)
#
#		Now it depends on the type
#
		if isinstance(item, (basestring, QString)):
			self.set_main(item)
			return
		if not isinstance(item, dict):
			return
		if item.has_key("scene"):
			self.set_scene(item["scene"])
		if item.has_key("text"):
			self.set_main(item["text"])
		if item.has_key("face"):
			self.set_face(item["face"])
		if item.has_key("name"):
			self.set_name(item["name"])
		if item.has_key("menu"):
			self.set_menu(item["menu"])
		if item.has_key("next"):
			self.script.extend(item["next"])




if __name__ == "__main__":
	import sys
	from glob import glob

	app = QtGui.QApplication(sys.argv)

	font_db = QtGui.QFontDatabase()
	font_db.addApplicationFont("resources/whitrabt.ttf")

	top = QtGui.QLabel()
	top.setGeometry(0, 0, 1024, 768)
	path = "resources/wood.jpg"
	top.setPixmap(QtGui.QPixmap(path))

	stage = StoryboxStage(top)

	be_my_guest = [
		"Why not stay with me as my guest? There is plenty "
		"of room in my tent, and I have grown to enjoy your "
		"company",

		"And I will admit a certain curiosity. I am fascinated "
		"by your plan, and I would dearly love to watch it unfold",

		{ "face" : None,
		  "name" : None,
		  "text" : "And so begins your first day in the city of "
		  "Abby's Crossing"
		},
		"Permit me to wish you the very best of luck.",
		"You're almost certainly going to need it!"
	]


	worse_odds = [
		{ "face" : "resources/hamid_face.png",
		  "name" : "Hamid",
		  "text" : "Truly, I admire your bravado! "
		},
		{ "next" : be_my_guest ,
		  "text" :
		  "But I fear that in your current state of health "
		  "you pose little danger to anyone"
		}
	]

	no_choice = [
		{ "face" : "resources/hamid_face.png",
		  "name" : "Hamid",
		  "text" : "Such fatalism ill-becomes you, my friend!"
		},


		{ "next" : be_my_guest,
		  "text" : 
		"Perhaps you will feel better after a good meal "
		"and a proper night's sleep.",
		}
	]

	not_without = [
		"You explain to Hamid that you did not lose "
		"everything to the desert.",

		"Inscribed on onion-skin paper and carefully "
		"concealed within a seam on your shirt, you "
		"carry a banker's letter",

		"If you can get to a bank, that alone should be "
		"enough to establish you with funds once again",

		{ "face" : "resources/hamid_face.png",
		  "name" : "Hamid",
		  "text" : "Then you will need to visit the Coin "
		  "Exchange!"
		},

		{ "next" : be_my_guest ,
		  "text" : 
		"Although dressed as you are now, you "
		"will be lucky to get through the Gate of Earth, "
		"let alone enter the Exchange.",
		}
	]

	script = [
		{ "scene" : "resources/opening.jpg",
		  "text" :
		"The plan was good: travel to the desert city of Abby's "
		"crossing, open a whorehouse, use the wealth of the "
		"organisation to take control of the city's prostitution",
		},

		"Then, with the resources of two cities to draw on, "
		"repeat the process with a third. Soon half a continent "
		"might fall under your control",

		{
			"scene" : "resources/caravan2.jpg" ,
			"text"	: 
			"You make arrangements to join a caravan due to "
			"depart for the Crossing."
		},

		"You take gold, and a hand picked contingent of whores "
		"and guards. ",

		"Nothing had been left to chance.", 


		{ "scene" : "resources/caravan3.jpg",
		  "text"  : "But then no one could have foreseen the storm.",
		},

		"For days the desert howled and clawed at your tent, "
		"demanding admission. Experienced caravaneers hardly "
		"dared leave their tents.",
		
		"Precious supplies of food and water dwindled.",

		"Finally, one night more than a week after the storm began, "
		"the winds abated. The caravaneers breathed a collective sigh "
		"of relief and began to make ready to resume their journey.",


		{ "scene" : "resources/caravan4.jpg",
		  "text"  : "Which was when the raiders attacked.",
		},

		"You remember very little of that night of blood and fire. ",

		"Were you victor or victim? Hero or coward? You remember a "
		"man's cry of rage, a woman's scream, but from whom they "
		"arose, you have no idea",

		"Eventually, you were found wanding the desert. Demented and "
		"raving, your companions lost to you.",

		{
			"scene" : "resources/caravan2.jpg" ,
			"text"	: 
		"Thanks to the kindness of Hamid, one of the desert "
		"tribesmen you came at last to the gates of Abby's crossing.",

		},


		"Weak from your ordeal, dressed in rags, and without a copper "
		"to your name, you must establish yourself in a strange city "
		"in the face of hostile competition",
		
		{ "face" : "resources/hamid_face.png",
		  "name" : "Hamid",
		  "text" : "Well, my friend, here we are in Abby's Crossing. "
		},

		"Are you determined to proceed with this course of action? ",

		"The odds against you are truly intimidating!",

		{ "face" : None,
		  "name" : None,
		  "menu" : [ (
			"Hah! I've faced worse odds than this!",
			worse_odds
		), (
			"I'm not entirely without resources, even now...",
			not_without
		), (
			"I don't see that I have much choice ...",
			no_choice
		) ],
		}
	]

	stage.play(script)

	def bye():
		QtCore.QCoreApplication.instance().quit()
	stage.ended.connect(bye)

	top.show()
	sys.exit(app.exec_())


